package cn.javacart.jopencart.validator;

import org.joda.time.DateTime;

import cn.javacart.jopencart.engine.JOpencartController;
import cn.javacart.jopencart.engine.JOpencartValidator;
import cn.javacart.jopencart.model.Customer;
import cn.javacart.jopencart.model.CustomerLogin;
import cn.javacart.jopencart.service.catalog.account.AccountCustomerService;

/**
 * 
 * @author farmer
 *
 */
public class AccountLoginValidator extends JOpencartValidator{

	@Override
	protected void doValidate(JOpencartController c) {
		if(c.isPost()){
			language.load("/catalog/language/{0}/account/login.php");
			String email = c.getPara("email");
			String password = c.getPara("password");
			CustomerLogin loginInfo = AccountCustomerService.ME.getLoginAttempts(email);
			if(loginInfo != null && loginInfo.getInt("total") > Integer.parseInt((String)config.get("config_login_attempts"))
					&&new DateTime().minusHours(1).getMillis() < loginInfo.getDate("date_modified").getTime()
					){
				addError("warning", language.getStr("error_attempts"));
			}
			Customer customerInfo = AccountCustomerService.ME.getCustomerByEmail(email);
			if(customerInfo != null && !customerInfo.getBoolean("approved")){
				addError("warning", language.getStr("error_approved"));
			}
			if(errMap.size() == 0){
				if(!customer.login(email, password)){
					addError("warning",language.getStr("error_login"));
					AccountCustomerService.ME.addLoginAttempt(email);
				}else{
					AccountCustomerService.ME.deleteLoginAttempts(email);
				}
			}
			
		}
	}
}
